package de.tsystems.jsfdict.api.impl;

import com.google.common.base.Preconditions;
import de.tsystems.jsfdict.api.TranslationService;
import de.tsystems.jsfdict.model.Language;
import de.tsystems.jsfdict.model.Translation;
import de.tsystems.jsfdict.model.Word;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;

@Named("translationService")
class TranslationServiceImpl implements TranslationService {

    @Inject
    @Named("transactionDao")
    private TranslationDao translationDao;

    @Override
    public void setTranslationDao(TranslationDao translationDao) {
        this.translationDao = translationDao;
    }

    @Override
    public TranslationDao getTranslationDao() {
        return translationDao;
    }

    @Transactional
    @Override
    public Translation save(@NotNull Translation translation) {
        return translationDao.save(translation);
    }

    @Override
    @Transactional(readOnly = true)
    public Translation getById(@NotNull Serializable id) {
        return translationDao.getById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Translation> listAll() {
        return translationDao.listAll();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Word> getTranslationWords(@NotNull Word word, @NotNull Language language) {
        Preconditions.checkNotNull(word.getId());
        Preconditions.checkNotNull(language.getId());
        return translationDao.getTranslationWords(word, language);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Word> getTranslationWords(@NotNull Word word) {
        Preconditions.checkNotNull(word.getId());
        return translationDao.getTranslationWords(word);
    }

    @Override
    @Transactional
    public boolean createTranslation(@NotNull Word left,@NotNull Word right) {
        Preconditions.checkNotNull(left.getId());
        Preconditions.checkNotNull(right.getId());
        if (translationDao.isTranslationExist(left, right)) {
            return false;
        }
        translationDao.create(left, right);
        return true;
    }

    @Override
    @Transactional
    public void remove(@NotNull Translation translation) {
        translationDao.remove(translation);
    }
}